﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Globals = DotNetNuke.Common.Globals;

using DotNetNuke.Security;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Framework;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.WebControls;
using System.Collections;
using DotNetNuke.UI.Utilities;

using BuSm = VLUNewsBusiness.VLUSitemap;
using BuNe = VLUNewsBusiness.VLUNews;
using BuUt = VLUNewsBusiness.Utilities;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Common.Utilities;
using System.IO;
using System.Web.UI.HtmlControls;

namespace VLUNewsUI.VLUNews
{
    public partial class HtmlContent : PortalModuleBase
    {
        #region Private Members
        private int _HtmlContentID = -1;
        private int _SitemapID = -1;
        private int _ParentID = -1;
        private int _Status = -1;
        private int _RoleID = -1;
        private bool _Sender = true;
        private string _ImageFolder = "Images/AnhDaiDien";
        private string _CommandName = string.Empty;

        #endregion

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            jQuery.RequestDnnPluginsRegistration();
            //HtmlGenericControl scriptInclude = (HtmlGenericControl)Page.Header.FindControl(ID + "popup");
            //if (scriptInclude == null)
            //{
            //    scriptInclude = new HtmlGenericControl("script");
            //    scriptInclude.Attributes["type"] = "text/javascript";
            //    scriptInclude.Attributes["src"] = this.ControlPath + "js/popup.js";
            //    scriptInclude.ID = ID + "popup";

            //    this.Page.Header.Controls.Add(scriptInclude);
            //}
        }// Init

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            cmdComment.Click += OnCommentClick;
            cmdUpdate.Click += OnUpdateClick;
            cmdGet.Click += OnGetClick;
            cmdSend.Click += OnSendClick;
            cmdReturn.Click += OnReturnClick;
            cmdApprove.Click += OnApproveClick;
            cmdDown.Click += OnDownClick;
            cmdDeleteTemp.Click += OnDeleteTempClick;
            cmdDelete.Click += OnDeleteClick;
            cmdCancel.Click += OnCancelClick;
            cmdSelectThemnail.Click += OnSelectThemnailClick;
            lblThemnailClose.Click += OnThemnailCloseClick;
            //cmdUploadThemnail.Click += OnUploadThemnailClick;
            urlUploadImage.PreRender += urlUploadImage_PreRender;
            urlUploadImage.Error += urlUploadImage_Error;


            dtlImages.ItemCommand += OnImagesItemCommand;
            ddlSitemapName.SelectedIndexChanged += ddlSitemapName_SelectedIndexChanged;
            //dgdSitemap.ItemCommand += OnDataGridSitemap_ItemCommand;
            //dgdSitemap.PreRender += OnSitemap_PreRender;
            //dtlParent.ItemCommand += OnParent_ItemCommand;

            try
            {
                if (!Page.IsPostBack)
                {
                    // Get request params and set ViewState.
                    if ((Request.QueryString["HtmlContentID"] != null))
                    {
                        _HtmlContentID = Int32.Parse(Request.QueryString["HtmlContentID"]);
                    }
                    ViewState["HtmlContentID"] = _HtmlContentID;
                    if ((Request.QueryString["Status"] != null))
                    {
                        _Status = Int32.Parse(Request.QueryString["Status"]);
                    }
                    ViewState["Status"] = _Status;
                    if ((Request.QueryString["RoleID"] != null))
                    {
                        _RoleID = Int32.Parse(Request.QueryString["RoleID"]);
                    }
                    ViewState["RoleID"] = _RoleID;
                    if ((Request.QueryString["Sender"] != null))
                    {
                        _Sender = Boolean.Parse(Request.QueryString["Sender"]);
                    }
                    ViewState["Sender"] = _Sender;
                    ViewState["SkipSender"] = 0;
                    if ((Request.QueryString["SkipSender"] != null))
                    {
                        ViewState["SkipSender"] = int.Parse(Request.QueryString["SkipSender"]);
                    }
                    ViewState["SkipReceiver"] = 0;
                    if ((Request.QueryString["SkipReceiver"] != null))
                    {
                        ViewState["SkipReceiver"] = int.Parse(Request.QueryString["SkipReceiver"]);
                    }
                    ViewState["ImageUrl"] = string.Empty;
                    // Add confirm message.
                    ClientAPI.AddButtonConfirm(cmdDeleteTemp, Localization.GetString("ConfirmDeleteTemp", LocalResourceFile));
                    ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("ConfirmDelete", LocalResourceFile));
                    // Get RoleID of User.
                    if (_RoleID == -1)
                    {
                        // Set default Role for this User.
                        var Roles = BuNe.HtmlContent.Instance().GetsRole(UserId);
                        if (Roles == null || Roles.Count < 1)
                        {
                            return;
                        }
                        // Get first RoleID.
                        _RoleID = int.Parse(Roles[0].GetValue(0).ToString());
                        ViewState["RoleID"] = _RoleID;
                    }
                    BindingSitemap();
                    // Create New
                    if (_HtmlContentID == -1)
                    {
                        //lstParent = BuSm.Sitemap.Instance().GetsParentByParentID(_SitemapID);
                        cmdDeleteTemp.Visible = false;
                        cmdSend.CausesValidation = cmdApprove.CausesValidation = true;
                        if (ddlSitemapName.Items.Count > 0)
                        {
                            ddlSitemapName.SelectedValue = "-1";
                            ddlSitemapName_SelectedIndexChanged(ddlSitemapName, null);
                            //valSitemapName.Visible = false;
                        }
                    }
                    else
                    {
                        Array vHtmlContent = BuNe.HtmlContent.Instance().GetStatus(_HtmlContentID, _Status);
                        if (vHtmlContent == null)
                            return;
                        _SitemapID = (int)vHtmlContent.GetValue(1);
                        ddlSitemapName.SelectedValue = _SitemapID.ToString();
                        ddlSitemapName_SelectedIndexChanged(ddlSitemapName, null);
                        //lstParent = BuSm.Sitemap.Instance().GetsParentByParentID(_SitemapID);
                        SetControlValues(vHtmlContent);
                        pnlComment.Visible = true;
                    }
                    BindingComment(_HtmlContentID);
                    CommandVisible(_Status);
                    //setDefaultImage();
                } //if (!Page.IsPostBack)
                else
                {
                    _HtmlContentID = int.Parse(ViewState["HtmlContentID"].ToString());
                    _Status = int.Parse(ViewState["Status"].ToString());
                    _RoleID = int.Parse(ViewState["RoleID"].ToString());
                    _Sender = bool.Parse(ViewState["Sender"].ToString());
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
            // Release Business Object.
            BuSm.Sitemap.Release();
        }

        #region Private Methods
/*
        void BindingDataGrid(int pSitemapID)
        {
            //ViewState["ParentID"] = pParentID;
            ViewState["SitemapID"] = pSitemapID;
            txtSitemapName.Text = BuSm.Sitemap.Instance().GetSitemapName(pSitemapID);
            dgdSitemap.DataSource = BuSm.Sitemap.Instance().GetsChildren(pSitemapID);
            Localization.LocalizeDataGrid(ref dgdSitemap, LocalResourceFile);
            dgdSitemap.DataBind();
        }
        void BindingDataList(IList pParents)
        {
            dtlParent.DataSource = pParents;
            dtlParent.DataBind();
        }
*/
        void ShowPanelIsSecurity(bool pIsSecurity)
        {
            imgIsSecurity.ImageUrl = ControlPath + "images/";
            imgIsSecurity.ImageUrl += pIsSecurity ? "Security.png" : "SecurityNone.png";
        }
        void BindingSitemap()
        {
            ddlSitemapName.DataValueField = "Key";
            ddlSitemapName.DataTextField = "Value";
            IList lstSitemap = BuSm.Sitemap.Instance().GetsAllShowList();
            lstSitemap.Insert(0, new KeyValuePair<int, string>(-1, ""));
            ddlSitemapName.DataSource = lstSitemap;
            ddlSitemapName.DataBind();
        }
        void BindingComment(int pHtmlContentID)
        {
            dgdComment.DataSource = BuNe.Comment.Instance().GetsByHtmlContentID(pHtmlContentID);
            Localization.LocalizeDataGrid(ref dgdComment, LocalResourceFile);
            dgdComment.DataBind();
        }
        void BindingThemnailImages()
        {
            //string upFolder = MapPath("~/Portal/" + PortalId + "/Images/AnhDaiDien");

            //DirectoryInfo dir = new DirectoryInfo(upFolder);
            //dtlImages.DataSource = dir.GetFiles();


            IFolderInfo folder = FolderManager.Instance.GetFolder(PortalId, "Images/AnhDaiDien");

            List<IFileInfo> files = FolderManager.Instance.GetFiles(folder).ToList();
            //foreach (var item in files)
            //{
            //    item.FileName
            //}


            dtlImages.DataSource = files;
            dtlImages.DataKeyField = "FileId";
            dtlImages.DataBind();
        }

        //void saveUploadedFile()
        //{
        //    IFolderInfo folder = FolderManager.Instance.GetFolder(PortalId, "Images/AnhDaiDien");
        //    if (FileManager.Instance.FileExists(folder, fupThemnail.FileName))
        //    {
        //        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("FileExist", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning);
        //    }
        //    else
        //    {
        //        //string s = FileSystemUtils.UploadFile(themnailFolder, fulThemnail.PostedFile);
        //        IFileInfo file = FileManager.Instance.AddFile(folder, fupThemnail.FileName, fupThemnail.FileContent, true);
        //        imgThemnail.ImageUrl = folder.FolderPath + file.FileName;
        //    }
        //    //string path = PortalSettings.HomeDirectoryMapPath;
        //    //string themnailFolder = path + "Images\\AnhDaiDien\\";
        //    //IFolderInfo folder = FolderManager.Instance.GetFolder(PortalId, themnailFolder);

        //    ////string s = FileSystemUtils.UploadFile(themnailFolder, fulThemnail.PostedFile);
        //    //IFileInfo file = FileManager.Instance.AddFile(folder, fupThemnail.FileName, fupThemnail.FileContent, true);
        //}
        void setDefaultImage()
        {
            string imageName = "Default.png";
            IFolderInfo folder = FolderManager.Instance.GetFolder(PortalId, _ImageFolder);
            if (!FileManager.Instance.FileExists(folder, imageName))
            {
                //IFileInfo file = FileManager.Instance.GetFile(folder, defaultImage);
                //urlUploadImage.Url = FileManager.Instance.GetUrl(file);
                //ViewState["ImageUrl"] = "FileID=" + file.FileId;
                //urlUploadImage.Url = ViewState["ImageUrl"].ToString();
                IFileInfo file = FileManager.Instance.GetFile(folder, imageName);
                ViewState["ImageUrl"] = "FileID=" + file.FileId;
                urlUploadImage.Url = ViewState["ImageUrl"].ToString();
            }
            imgThemnail.ImageUrl = getImageUrl(imageName);
        }

        string getImageUrl(string imageName)
        {
            return "/Portals/" + PortalId + "/" + _ImageFolder + "/" + imageName;
        }

        void SetControlValues(Array pModel)
        {
            if (pModel == null)
            {
                txtTitle.Text = 
                txtDescription.Text = 
                imgThemnail.ImageUrl = string.Empty;
                txtContent.Text = string.Empty;
            }
            else
            {
                txtTitle.Text = pModel.GetValue(3).ToString();
                txtDescription.Text = pModel.GetValue(4).ToString();
                // Not allow Update.
                if ((_Status == (int)BuUt.StatusEnums.Sent)// Wating and receiver
                    || (_Status == (int)BuUt.StatusEnums.Returned && _Sender)
                    || (_Status == (int)BuUt.StatusEnums.Approved)
                    || (_Status == (int)BuUt.StatusEnums.Downed)
                    || (_Status == (int)BuUt.StatusEnums.Deleted))
                {
                    lblContent.Text = Server.HtmlDecode(pModel.GetValue(5).ToString());
                    lblContent.Visible = true;
                    txtContent.Visible = valContent.Visible = false;
                }
                else // Allow Update
                {
                    txtContent.Text = pModel.GetValue(5).ToString();
                    txtContent.Visible = valContent.Visible = true;
                    lblContent.Visible = false;
                }
                imgThemnail.ImageUrl = pModel.GetValue(6).ToString(); //.Substring(9);
                string imgUrl = imgThemnail.ImageUrl;
                imgUrl = imgUrl.Substring(imgUrl.IndexOf(_ImageFolder));
                //IFolderInfo folder = FolderManager.Instance.GetFolder(PortalId, "Images/AnhDaiDien");
                //IFileInfo file = (IFileInfo)FileManager.Instance.GetFile(PortalId, imgUrl);
                IFileInfo file = (IFileInfo)FileManager.Instance.GetFile(PortalId, imgUrl);
                if (file != null)
                {
                    ViewState["ImageUrl"] = "FileID=" + file.FileId;
                    urlUploadImage.Url = "FileID=" + file.FileId;
                }
            }
        }

        void CommandVisible(int pStatus)
        {
            // Create New
            if (_HtmlContentID == -1)
            {
                cmdDeleteTemp.Visible = false;
                cmdSend.CausesValidation = cmdApprove.CausesValidation = true;
            }
            else
            {
                pnlComment.Visible = true;
            }
            // Case Status
            switch (pStatus)
            {
                case (int)BuUt.StatusEnums.Editing:
                    {
                        cmdUpdate.Visible = true;
                        if (_HtmlContentID > -1)
                            cmdDeleteTemp.Visible = true;
                        cmdApprove.Visible = BuNe.HtmlContent.Instance().CheckAllowToApprove(_RoleID, _SitemapID);
                        //if (vIsApprove)
                        //    cmdApprove.Visible = true;
                        //if (_Sender) // Sender.
                        //    cmdApprove.Visible = true;
                        cmdSend.Visible = !BuNe.HtmlContent.Instance().CheckTopRole(_RoleID);
                        //if (!BuNe.HtmlContent.Instance().CheckTopRole(_RoleID))
                        //    cmdSend.Visible = true;
                        break;
                    }
                case (int)BuUt.StatusEnums.Sent:
                    {
                        pnlCommentCommand.Visible = true;
                        if (_Sender)
                        {
                            SetEnableEditing(false);
                            cmdUpdate.Visible = false;
                            cmdGet.Visible = false;
                            cmdReturn.Visible = false;
                            cmdSend.Visible = false;
                            cmdApprove.Visible = false;
                        }
                        else
                        {
                            SetEnableEditing(false);
                            cmdUpdate.Visible = false;
                            cmdGet.Visible = true;
                            cmdReturn.Visible = true;
                            cmdSend.Visible = !BuNe.HtmlContent.Instance().CheckTopRole(_RoleID);
                            cmdApprove.Visible = BuNe.HtmlContent.Instance().CheckAllowToApprove(_RoleID, _SitemapID);
                        }
                        //cmdApprove.Visible = BuNe.HtmlContent.Instance().CheckAllowToApprove(_RoleID, _SitemapID);
                        //cmdSend.Visible = !BuNe.HtmlContent.Instance().CheckTopRole(_RoleID);
                        //cmdReturn.Visible = !_Sender;
                        ////cmdUpdate.Visible = false;
                        //if (!_Sender) // Receiver.
                        //{
                        //    cmdGet.Visible = true;
                        //}
                        break;
                    }
                case (int)BuUt.StatusEnums.Returned:
                    {
                        if (_Sender)
                        {
                            SetEnableEditing(false);
                            cmdUpdate.Visible = false;
                            cmdGet.Visible = false;
                            cmdReturn.Visible = false;
                            cmdSend.Visible = false;
                            cmdApprove.Visible = false;
                        }
                        else
                        {
                            cmdUpdate.Visible = true;
                            cmdGet.Visible = false;
                            cmdReturn.Visible = BuNe.HtmlContent.Instance().CheckReceiver(_HtmlContentID, UserId);
                            cmdSend.Visible = !BuNe.HtmlContent.Instance().CheckTopRole(_RoleID);
                            cmdApprove.Visible = BuNe.HtmlContent.Instance().CheckAllowToApprove(_RoleID, _SitemapID);
                        }
                        //cmdUpdate.Visible = cmdSend.Visible = !_Sender;
                        //if (!_Sender) // Receiver.
                        //    cmdApprove.Visible = BuNe.HtmlContent.Instance().CheckAllowToApprove(_RoleID, _SitemapID);
                        break;
                    }
                case (int)BuUt.StatusEnums.Approved:
                    {
                        //if (BuNe.HtmlContent.Instance().CheckAllowToDown(_HtmlContentID, UserId, _RoleID)) // Sender or TopRole.
                        cmdDown.Visible = BuNe.HtmlContent.Instance().CheckAllowToDown(_HtmlContentID, UserId, _RoleID);
                        SetEnableEditing(false);
                        break;
                    }
                case (int)BuUt.StatusEnums.Downed:
                    {
                        //if (BuNe.HtmlContent.Instance().CheckAllowToDown(_HtmlContentID, UserId, _RoleID)) // Sender or TopRole.
                        //    cmdUpdate.Visible = cmdApprove.Visible = true;
                        cmdDeleteTemp.Visible = true;
                        SetEnableEditing(false);
                        break;
                    }
                case (int)BuUt.StatusEnums.Deleted:
                    {
                        //cmdUpdate.Visible = cmdApprove.Visible = true;
                        cmdDelete.Visible = true;
                        SetEnableEditing(false);
                        break;
                    }
            }
        }

        void SetEnableEditing(bool pEnable)
        {
            ddlSitemapName.Enabled = txtTitle.Enabled = txtDescription.Enabled = pEnable;
            pnlCommandThemnail.Visible =
            pnlCommandPaste.Visible = pEnable;
            if (pEnable)
            {
                divUrlUploadImage.Style["display"] = "block";
            }
            else
            {
                divUrlUploadImage.Style["display"] = "none";
            }
            //cmdSelectThemnail.Visible = urlUploadImage.Visible = pEnable;
            //cmdSelectThemnail.Enabled = pEnable;
            //((System.Web.UI.WebControls.WebControl)(urlUploadImage.FindControl("cmdUpload"))).Enabled = pEnable;
        }

        int SaveNew()
        {
            int reslult = -100;// Not Page.IsValid
            if (Page.IsValid)
            {
                _SitemapID = int.Parse(ViewState["SitemapID"].ToString());
                string imageUrl = imgThemnail.ImageUrl;
                imageUrl = getImageUrl(imageUrl.Substring(imageUrl.LastIndexOf("/") + 1));
                reslult = BuNe.HtmlContent.Instance().SaveNew(_HtmlContentID, PortalId, _SitemapID, txtTitle.Text, txtDescription.Text, txtContent.Text, imageUrl, UserId);
            }
            return reslult;
        }

        int SaveEditing()
        {
            int reslult = -100;// Not Page.IsValid
            if (Page.IsValid)
            {
                _HtmlContentID = int.Parse(ViewState["HtmlContentID"].ToString());
                _SitemapID = int.Parse(ViewState["SitemapID"].ToString());
                string imageUrl = imgThemnail.ImageUrl;
                imageUrl = getImageUrl(imageUrl.Substring(imageUrl.LastIndexOf("/") + 1));
                reslult = BuNe.HtmlContent.Instance().SaveEditing(_HtmlContentID, _SitemapID, txtTitle.Text, txtDescription.Text, txtContent.Text, imageUrl, UserId);
            }
            return reslult;
        }

        int SaveGet()
        {
            int reslult = BuNe.HtmlContent.Instance().SaveGet(_HtmlContentID, UserId);
            return reslult;
        }
        #endregion

        #region Event Handlers
        protected void OnSelectThemnailClick(object sender, EventArgs e)
        {
            try
            {
                divThemnailImages.Visible = true;
                BindingThemnailImages();
                popupboxPaste.Style["display"] = "none";
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        protected void OnThemnailCloseClick(object sender, EventArgs e)
        {
            try
            {
                divThemnailImages.Visible = false;
                //cmdPastShow.Attributes.Add("onclick", "cmdPastShow()");
                popupboxPaste.Style["display"] = "none";
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        //protected void OnUploadThemnailClick(object sender, EventArgs e)
        //{
        //    //uploadFile
        //    try
        //    {
        //        if (fupThemnail.HasFile)
        //        {
        //            IFolderInfo folder = FolderManager.Instance.GetFolder(PortalId, "Images/AnhDaiDien");
        //            if (FileManager.Instance.FileExists(folder, fupThemnail.FileName))
        //            {
        //                DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("FileExist", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning);
        //            }
        //            else
        //            {
        //                //string s = FileSystemUtils.UploadFile(themnailFolder, fulThemnail.PostedFile);
        //                IFileInfo file = FileManager.Instance.AddFile(folder, fupThemnail.FileName, fupThemnail.FileContent, true);
        //                imgThemnail.ImageUrl = folder.FolderPath + file.FileName;
        //            }
        //        }
        //    }
        //    catch (Exception exc) //Module failed to load
        //    {
        //        Exceptions.ProcessModuleLoadException(this, exc);
        //    }
        //}

        void urlUploadImage_Error(object sender, EventArgs e)
        {
            
        }
        protected void OnImagesItemCommand(object source, DataListCommandEventArgs e)
        {
            imgThemnail.ImageUrl = ((System.Web.UI.WebControls.Image)(e.CommandSource)).ImageUrl;
            divThemnailImages.Visible = false;
            ////dtlImages.SelectedValue
            //IFolderInfo folder = FolderManager.Instance.GetFolder(PortalId, "Images/AnhDaiDien");
            //string fileName = url.Substring(url.LastIndexOf("/") + 1);
            //if (FileManager.Instance.FileExists(folder, fileName))
            //{
            //    IFileInfo file = FileManager.Instance.GetFile(folder, fileName);
            //    //urlUploadImage.Url = FileManager.Instance.GetUrl(file);
            //    ViewState["ImageUrl"] = "FileID=" + file.FileId;
            //    urlUploadImage.Url = ViewState["ImageUrl"].ToString();
            //    imgThemnail.ImageUrl = "~/Portals/" + PortalId + "/" + folder.FolderPath + fileName;
            //    imgCommand = true;
            //    divThemnailImages.Visible = false;
            //}
        }
        void urlUploadImage_PreRender(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewState["ImageUrl"] = string.Empty;
                string imageName = "Default.png";
                if (_HtmlContentID == -1)
                {
                    imgThemnail.ImageUrl = getImageUrl(imageName);
                }
                IFolderInfo folder = FolderManager.Instance.GetFolder(PortalId, _ImageFolder);
                if (FileManager.Instance.FileExists(folder, imageName))
                {
                    IFileInfo file = FileManager.Instance.GetFile(folder, imageName);
                    ViewState["ImageUrl"] = "FileID=" + file.FileId;
                    urlUploadImage.Url = ViewState["ImageUrl"].ToString();
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(urlUploadImage.Url))
                {
                    urlUploadImage.Url = ViewState["ImageUrl"].ToString();
                }
                else if (!urlUploadImage.Url.Equals(ViewState["ImageUrl"].ToString()))
                {
                    ViewState["ImageUrl"] = urlUploadImage.Url;
                    int FileID = int.Parse(urlUploadImage.Url.Substring(urlUploadImage.Url.IndexOf("=") + 1));
                    IFileInfo file = FileManager.Instance.GetFile(FileID);
                    imgThemnail.ImageUrl = FileManager.Instance.GetUrl(file); ;
                }
            }

            // Hide   
            urlUploadImage.FindControl("cboFolders").Visible =
            urlUploadImage.FindControl("cboImages").Visible =
            urlUploadImage.FindControl("cboFiles").Visible =
            urlUploadImage.FindControl("cboUrls").Visible =
            urlUploadImage.FindControl("cboTabs").Visible =
            urlUploadImage.FindControl("lblFolder").Visible =
            urlUploadImage.FindControl("lblFile").Visible = false;
            urlUploadImage.FindControl("FileRow").FindControl("cboFiles").Visible = false;


            //foreach (var item in urlUploadImage.Controls)
            //{
            //    if (item is DropDownList)
            //    {
            //        (item as DropDownList).Visible = false;
            //    }
            //}
            //(urlUploadImage.FindControl("cmdCancel") as LinkButton).Text = "Đóng";
            //foreach (var item in ((System.Web.UI.WebControls.WebControl)(urlUploadImage.FindControl("FileRow"))).Controls)
            //{
            //    if (item is DropDownList)
            //    {
            //        (item as DropDownList).Visible = false;
            //    }
            //}
            //foreach (var item in ((System.Web.UI.WebControls.WebControl)(urlUploadImage.FindControl("ImagesRow"))).Controls)
            //{
            //    if (item is DropDownList)
            //    {
            //        (item as DropDownList).Visible = false;
            //    }
            //}
        }

        void ddlSitemapName_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int vSitemapID = int.Parse(ddlSitemapName.SelectedValue);
                ViewState["SitemapID"] = vSitemapID;
                cmdApprove.Visible = cmdSend.Visible = false;
                if (vSitemapID == -1)
                {
                    valSitemapName.IsValid = 
                    imgIsSecurity.Visible = false;
                }
                else
                {
                    valSitemapName.IsValid = 
                    imgIsSecurity.Visible = true;
                    bool vIsSecurity = BuSm.Sitemap.Instance().GetIsSecurity(vSitemapID);
                    ShowPanelIsSecurity(vIsSecurity);
                    if (_Status == (int)BuUt.StatusEnums.Editing || _Status == (int)BuUt.StatusEnums.Sent)
                    {
                        cmdApprove.Visible = BuNe.HtmlContent.Instance().CheckAllowToApprove(int.Parse(ViewState["RoleID"].ToString()), vSitemapID);
                    }
                    if (_Status == (int)BuUt.StatusEnums.Editing)
                        cmdSend.Visible = !cmdApprove.Visible;
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
/*
        protected void OnSitemap_PreRender(object sender, EventArgs e)
        {
            if (!(_CommandName.Equals("Up") || _CommandName.Equals("Down")))
                dgdSitemap.SelectedIndex = -1;
        }

        protected void OnParent_ItemCommand(object source, DataListCommandEventArgs e)
        {
            _CommandName = e.CommandName;
            _SitemapID = Int32.Parse(e.CommandArgument.ToString());
            ViewState["SitemapID"] = _SitemapID;
            cmdApprove.Visible = BuNe.HtmlContent.Instance().CheckAllowToApprove(int.Parse(ViewState["RoleID"].ToString()), _SitemapID);
            //_ParentID = iSitemapID;
            //ViewState["ParentID"] = _ParentID;
            List<KeyValuePair<int, string>> lst = new List<KeyValuePair<int, string>>();
            foreach (DataListItem item in dtlParent.Items)
            {
                CommandButton cmd = (CommandButton)item.Controls[1];
                lst.Add(new KeyValuePair<int, string>(int.Parse(cmd.CommandArgument), cmd.Text));
                if (item == e.Item)
                {
                    break;
                }
            }

            BindingDataList(lst);

            BindingDataGrid(_SitemapID);
        }

        protected void OnDataGridSitemap_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Select":
                    {
                        OnSelectCommand(source, e);
                        break;
                    }
            }
        }

        protected void OnSelectCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                _SitemapID = Int32.Parse(e.CommandArgument.ToString());
                ViewState["SitemapID"] = _SitemapID;
                cmdApprove.Visible = BuNe.HtmlContent.Instance().CheckAllowToApprove(int.Parse(ViewState["RoleID"].ToString()), _SitemapID);
                //string sSitemapName = e.Item.Cells[1].Text;
                string sSitemapName = ((LinkButton)(e.CommandSource)).Text;
                List<KeyValuePair<int, string>> lst = new List<KeyValuePair<int, string>>();
                foreach (DataListItem item in dtlParent.Items)
                {
                    CommandButton cmd = (CommandButton)item.Controls[1];
                    lst.Add(new KeyValuePair<int, string>(int.Parse(cmd.CommandArgument), cmd.Text));
                }
                lst.Add(new KeyValuePair<int, string>(_SitemapID, sSitemapName));

                BindingDataList(lst);
                // Binding data grid.
                BindingDataGrid(_SitemapID);
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
*/
        protected void OnCommentClick(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(txtComment.Text))
                {
                    int reslult = BuNe.Comment.Instance().Save(_HtmlContentID, txtComment.Text.Trim(), UserId);
                    if (reslult < 0) // Error.
                    {
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                    else
                    {
                        txtComment.Text = string.Empty;
                        BindingComment(_HtmlContentID);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnGetClick(object sender, EventArgs e)
        {
            try
            {
                _HtmlContentID = SaveGet();
                if (_HtmlContentID < 0) // Error.
                {
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    return;
                }
                else
                {
                    ViewState["HtmlContentID"] = _HtmlContentID;
                }
                SetEnableEditing(true);
                cmdUpdate.Visible = true;
                cmdGet.Visible = cmdReturn.Visible = false;
                txtContent.Text = Server.HtmlEncode(lblContent.Text);
                txtContent.Visible = true;
                lblContent.Visible = false;
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdUpdate_Click runs when the update Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// 	[jlucarino]	2/23/2009	Added CreatedByUserID and LastModifiedByUserID
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnUpdateClick(object sender, EventArgs e)
        {
            try
            {
                if (_HtmlContentID == -1)// New
                {
                    // Save New.
                    _HtmlContentID = SaveNew();
                }
                else
                {
                    // Save Editing.
                    _HtmlContentID = SaveEditing();
                }
                if (_HtmlContentID < 0) // Error.
                {
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    return;
                }
                else // Success.
                {
                    ViewState["HtmlContentID"] = _HtmlContentID;
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaved", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess);
                    //Response.Redirect(Globals.NavigateURL("", "HtmlContentID=" + _HtmlContentID, "RoleID=" + ViewState["RoleID"], "Status=" + _Status));
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnSendClick(object sender, EventArgs e)
        {
            try
            {
                if (txtTitle.Enabled)
                {
                    if (_HtmlContentID == -1)// New
                    {
                        // Save New.
                        _HtmlContentID = SaveNew();
                    }
                    else
                    {
                        // Save Editing.
                        _HtmlContentID = SaveEditing();
                    }
                    if (_HtmlContentID < 0) // Error.
                    {
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }
                    else
                    {
                        ViewState["HtmlContentID"] = _HtmlContentID;
                    }
                }
                // Save Sent.
                // Get all roles which user can send to.
                var Roles = BuNe.HtmlContent.Instance().GetsToRole(int.Parse(ViewState["RoleID"].ToString()));
                if (Roles == null || Roles.Count < 1)
                {
                    return;
                }
                int vToRoleID = int.Parse(Roles[0].GetValue(0).ToString());
                // Save user to role.
                int reslult = BuNe.HtmlContent.Instance().SaveSentToRole(_HtmlContentID, UserId, vToRoleID);
                if (reslult != 1) // Error.
                {
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                }
                else // Success.
                {
                    Response.Redirect(Globals.NavigateURL("", "HtmlContentID=" + _HtmlContentID, "RoleID=" + ViewState["RoleID"], "Status=" + _Status, "SkipSender=" + ViewState["SkipSender"], "SkipReceiver=" + ViewState["SkipReceiver"]));
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnApproveClick(object sender, EventArgs e)
        {
            try
            {
                if (txtTitle.Enabled)
                {
                    if (_HtmlContentID == -1)// New
                    {
                        // Save New.
                        _HtmlContentID = SaveNew();
                    }
                    else
                    {
                        // Save Editing.
                        _HtmlContentID = SaveEditing();
                    }
                    if (_HtmlContentID < 0) // Error.
                    {
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }
                    else
                    {
                        ViewState["HtmlContentID"] = _HtmlContentID;
                    }
                }
                // Save Approve.
                int reslult = BuNe.HtmlContent.Instance().SaveApproved(_HtmlContentID, UserId);
                if (reslult != 1) // Error.
                {
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                }
                else // Success.
                {
                    Response.Redirect(Globals.NavigateURL("", "HtmlContentID=" + _HtmlContentID, "RoleID=" + ViewState["RoleID"], "Status=" + _Status, "SkipSender=" + ViewState["SkipSender"], "SkipReceiver=" + ViewState["SkipReceiver"]));
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnReturnClick(object sender, EventArgs e)
        {
            try
            {
                if (txtTitle.Enabled)
                {
                    if (_HtmlContentID == -1)// New
                    {
                        // Save New.
                        _HtmlContentID = SaveNew();
                    }
                    else
                    {
                        // Save Editing.
                        _HtmlContentID = SaveEditing();
                    }
                    if (_HtmlContentID < 0) // Error.
                    {
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }
                    else
                    {
                        ViewState["HtmlContentID"] = _HtmlContentID;
                    }
                }
                int reslult = BuNe.HtmlContent.Instance().SaveReturned(_HtmlContentID, UserId);
                if (reslult != 1) // Error.
                {
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                }
                else // Success.
                {
                    Response.Redirect(Globals.NavigateURL("", "HtmlContentID=" + _HtmlContentID, "RoleID=" + ViewState["RoleID"], "Status=" + _Status, "SkipSender=" + ViewState["SkipSender"], "SkipReceiver=" + ViewState["SkipReceiver"]));
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnDownClick(object sender, EventArgs e)
        {
            try
            {
                //if (Page.IsValid)
                {
                    int reslult = BuNe.HtmlContent.Instance().SaveDowned(_HtmlContentID, UserId);
                    if (reslult != 1) // Error.
                    {
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                    else // Success.
                    {
                        Response.Redirect(Globals.NavigateURL("", "HtmlContentID=" + _HtmlContentID, "RoleID=" + ViewState["RoleID"], "Status=" + _Status, "SkipSender=" + ViewState["SkipSender"], "SkipReceiver=" + ViewState["SkipReceiver"]));
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnDeleteTempClick(object sender, EventArgs e)
        {
            try
            {
                //if (Page.IsValid)
                {
                    int reslult = BuNe.HtmlContent.Instance().SaveDeleted(_HtmlContentID, UserId);
                    if (reslult != 1) // Error.
                    {
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("HtmlContentSaveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                    else // Success.
                    {
                        Response.Redirect(Globals.NavigateURL("", "HtmlContentID=" + _HtmlContentID, "RoleID=" + ViewState["RoleID"], "Status=" + _Status, "SkipSender=" + ViewState["SkipSender"], "SkipReceiver=" + ViewState["SkipReceiver"]));
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnDeleteClick(object sender, EventArgs e)
        {
            try
            {
                int reslult = BuNe.HtmlContent.Instance().Delete(_HtmlContentID);
                switch (reslult)
                {
                    case 0:
                    case -1:
                        {
                            DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ErrorSave", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                            break;
                        }
                    case 1: // Success.
                        {
                            Response.Redirect(Globals.NavigateURL("", "HtmlContentID=" + _HtmlContentID, "RoleID=" + ViewState["RoleID"], "Status=" + _Status, "SkipSender=" + ViewState["SkipSender"], "SkipReceiver=" + ViewState["SkipReceiver"]));
                            break;
                        }
                    case 2:
                        {
                            DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ErrorDeleteHaveChild", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                            break;
                        }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnCancelClick(object sender, EventArgs e)
        {
            Response.Redirect(Globals.NavigateURL("", "HtmlContentID=" + _HtmlContentID, "RoleID=" + ViewState["RoleID"], "Status=" + _Status, "SkipSender=" + ViewState["SkipSender"], "SkipReceiver=" + ViewState["SkipReceiver"]));
        }

        #endregion
    }
}